package com.icekrvams.air.installreferrer

import android.content.Context
import android.content.pm.PackageManager
import android.util.Base64
import android.util.Log
import java.security.MessageDigest

/**
 * author : She Wenbiao
 * date   : 2020/6/11 11:12 AM
 */
internal object PiracyChecker {

    fun verifyAppSignature(
        context: Context,
        targetSignature: String,
        showSignatureLog: Boolean
    ): Boolean {
        try {
            val packageInfo = context.packageManager
                .getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
            for (signature in packageInfo.signatures) {
                val md = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                val currentSignature =
                    Base64.encodeToString(md.digest(), Base64.DEFAULT).trim { it <= ' ' }
                if (showSignatureLog) {
                    Log.d("PiracyChecker", currentSignature)
                }
                // compare signatures
                if (targetSignature.trim { it <= ' ' } == currentSignature) {
                    return true
                }
            }
        } catch (e: Exception) {
            // assumes an issue in checking signature., but we let the caller decide on what to do.
        }
        return false
    }

    private val PLAY_STORE_APP_IDS = arrayOf(
        "com.android.vending",
        "com.google.android.feedback"
    )

    fun verifyInstaller(context: Context): Boolean {
        val list = listOf(*PLAY_STORE_APP_IDS)
        val installer = context.packageManager
            .getInstallerPackageName(context.packageName)
        return installer != null && list.contains(installer)
    }
}